﻿using System;
using LoungeRepo.Contracts.Core;

namespace LoungeRepo.Normalizer
{
    partial class ObjectGraphNormalizer
    {
        private bool TryNormalizeArrayValue(object value, out object normalizedValue)
        {
            if (value != null && value.GetType().IsArray)
            {
                if (IsSimpleType(value.GetType().GetElementType()))
                    normalizedValue = value;
                else
                    normalizedValue = NormalizeArray((Array)value);
                return true;
            }

            normalizedValue = null;
            return false;
        }

        private bool IsComplexArrayType(object value)
        {
            return value.GetType().IsArray && !IsSimpleType(value.GetType().GetElementType());
        }

        
        private bool TryNormalizeSimpleTypeValue(object value, out object normalizedValue)
        {
            normalizedValue = value;
            return value == null || IsSimpleType(value.GetType());
        }

        private bool IsSimpleType(Type type)
        {
            return type.IsPrimitive ||
                   type.IsEnum ||
                   type == typeof(string) ||
                   type == typeof(decimal) ||
                   type == typeof(DateTime);
        }


        private object NormalizeComplexTypeValue(object value)
        {
            if (this.normalizedObjectCache.ContainsKey(value))
                return this.normalizedObjectCache[value];

            ILoungeRepoEntityIdentity entityIdentity;
            if (TryExtractEntityIdentity(value, out entityIdentity))
                return NormalizeEntity(value, entityIdentity);

            return NormalizeNonEntity(value);
        }
    }
}
